from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from areas.models import Area


class AreaView(View):
    def get(self, request):

        area_id = request.GET.get("area_id")

        if not area_id:
            province_list = cache.get("province_list")
            if province_list:
                data = {"code": "0", "errmsg": "OK", "province_list": province_list}
                return JsonResponse(data)

            province_list = list()

            areas = Area.objects.filter(parent_id__isnull=True)

            for area in areas:
                area_dict = {
                    "id": area.id,
                    "name": area.name}
                province_list.append(area_dict)

            data = {"code": "0", "errmsg": "OK", "province_list": province_list}

            cache.set("province_list", province_list, 3600*24*2)

            return JsonResponse(data)

        else:

            area = Area.objects.get(id=area_id)

            # 搜索是否有缓存
            sub_data = cache.get("sub_data_%s" % area_id)
            if sub_data:
                data = {"code": "0", "errmsg": "OK", "sub_data": sub_data}
                return JsonResponse(data)

            sub_list = list()
            areas = area.sub.all()

            for sub in areas:
                area_dict = {
                    "id":sub.id,
                    "name":sub.name
                }
                sub_list.append(area_dict)

            sub_data = {"id":area.id,
                        "name":area.name,
                        "subs":sub_list}
            cache.set("sub_data_%s" % area_id, sub_data, 3600*24*2)

            data = {"code":"0","errmsg":"OK","sub_data":sub_data}

            return JsonResponse(data)
